<!--
 * @Description:
 * @Author: 月间
 * @Date: 2024-12-08 22:03:22
 * @LastEditTime: 2025-05-13 00:01:02
 * @LastEditors:
-->
<script setup lang="tsx">
import { NButton, NPopconfirm, NTag } from 'naive-ui';
import { useBoolean } from '@sa/hooks';
import { ref } from 'vue';
import type { UploadCustomRequestOptions, UploadFileInfo, UploadSettledFileInfo } from 'naive-ui';
import SvgIcon from '@/components/custom/svg-icon.vue';
import { fetchDeleteResource, fetchGetResourceList, fetchUploadResource } from '@/service/api';
import { useAppStore } from '@/store/modules/app';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { $t } from '@/locales';
import { useAuth } from '@/hooks/business/auth';

const { hasAuth } = useAuth();

const appStore = useAppStore();
/** is super role in static route */
const { VITE_STATIC_SUPER_ROLE } = import.meta.env;

const {
  columns,
  columnChecks,
  data,
  loading,
  getData,
  getDataByPage,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: fetchGetResourceList,
  apiParams: {
    current: 1,
    size: 10,
    // if you want to use the searchParams in Form, you need to define the following properties, and the value is null
    // the value can not be undefined, otherwise the property in Form will not be reactive
    filename: null,
    fileType: null
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'index',
      title: $t('common.index'),
      width: 64,
      align: 'center'
    },
    {
      key: 'filename',
      title: '原名称',
      align: 'center',
      minWidth: 100
    },
    {
      key: 'fileType',
      title: '资源类型',
      align: 'center',
      minWidth: 80
    },
    {
      key: 'url',
      title: '展示',
      minWidth: 120,
      render: row => {
        const iconMap = {
          image: { icon: 'ic:outline-image', color: 'text-primary' },
          video: { icon: 'mdi:video-outline', color: 'text-purple' },
          audio: { icon: 'mdi:music-note-outline', color: 'text-blue' },
          excel: { icon: 'mdi:microsoft-excel', color: 'text-green' },
          pdf: { icon: 'mdi:file-pdf-box', color: 'text-red' },
          word: { icon: 'mdi:microsoft-word', color: 'text-blue' },
          other: { icon: 'mdi:file-outline', color: 'text-gray' }
        };
        const fileType = (row.fileType?.toLowerCase() as keyof typeof iconMap) || 'other';
        const icon = iconMap[fileType] || iconMap.other;

        return fileType === 'image' ? (
          <n-image
            width="100"
            src={row.url}
            fallback-src="https://07akioni.oss-cn-beijing.aliyuncs.com/07akioni.jpeg"
          />
        ) : (
          <div class="flex items-center gap-2">
            <SvgIcon icon={icon.icon} class={`text-24px ${icon.color}`} />
            <n-button text tag="a" href={row.url} target="_blank" type="primary">
              查看文件
            </n-button>
          </div>
        );
      }
    }
  ]
});

const {
  drawerVisible,
  operateType,
  editingData,
  handleAdd,
  handleEdit,
  checkedRowKeys,
  onBatchDeleted,
  onDeleted
  // closeDrawer
} = useTableOperate(data, getData);

async function handleBatchDelete() {
  // request
  console.log(checkedRowKeys.value);
  const { error } = await fetchDeleteResource(checkedRowKeys.value);
  if (error) return;
  onBatchDeleted();
}

function handleDelete(id: number) {
  // request
  console.log(id);

  onDeleted();
}
function handleMenu(id: number) {
  roleId.value = id;
  openMenuAuthModal();
}
function handleButton(id: number) {
  roleId.value = id;
  openButtonAuthModal();
}

function edit(id: number) {
  handleEdit(id);
}
const roleId = ref<number>(-1);
const { bool: menuAuthVisible, setTrue: openMenuAuthModal } = useBoolean();
const { bool: buttonAuthVisible, setTrue: openButtonAuthModal } = useBoolean();
const showModal = ref(false);

function onNegativeClick() {
  showModal.value = false;
}
function onPositiveClick() {
  showModal.value = false;
}

function createThumbnailUrl(file: File | null, fileInfo: UploadSettledFileInfo): Promise<string> | undefined {
  if (!file) return undefined;
  return new Promise(resolve => {
    resolve(fileInfo.url as string);
  });
}
const customRequest = ({
  file,
  data,
  headers,
  withCredentials,
  action,
  onFinish,
  onError,
  onProgress
}: UploadCustomRequestOptions) => {
  const formData = new FormData();
  formData.append('file', file.file as File);
  // 添加path参数
  formData.append('path', 'test');
  fetchUploadResource(formData)
    .then(res => {
      // console.log(res);
      const url = res.data?.data as string | null;
      file.url = url;
      onFinish();
      window.$message?.success('上传成功');
    })
    .catch(err => {
      onError();
    });
};
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <RoleSearch v-model:model="searchParams" @reset="resetSearchParams" @search="getDataByPage" />
    <NCard title="资源列表" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          @refresh="getData"
        >
          <template #prefix>
            <NButton
              v-if="hasAuth('system:resource:upload')"
              size="small"
              ghost
              type="success"
              @click="showModal = true"
            >
              <template #icon>
                <icon-flat-color-icons:upload class="text-icon" />
              </template>
              上传文件
            </NButton>
            <NPopconfirm v-if="hasAuth('system:resource:delete')" @positive-click="handleBatchDelete">
              <template #trigger>
                <NButton size="small" ghost type="error" :disabled="checkedRowKeys.length === 0">
                  <template #icon>
                    <icon-ic-round-delete class="text-icon" />
                  </template>
                  {{ $t('common.batchDelete') }}
                </NButton>
              </template>
              {{ $t('common.confirmDelete') }}
            </NPopconfirm>
          </template>
        </TableHeaderOperation>
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="702"
        :loading="loading"
        remote
        :row-key="row => row.id"
        :pagination="mobilePagination"
        class="sm:h-full"
      />
    </NCard>
    <!-- 上传模态框 -->
    <NModal
      v-model:show="showModal"
      :mask-closable="false"
      preset="dialog"
      title="上传"
      content="你确认"
      negative-text="取消"
      @positive-click="onPositiveClick"
      @negative-click="onNegativeClick"
    >
      <NUpload
        multiple
        :custom-request="customRequest"
        directory-dnd
        :max="5"
        list-type="image"
        :create-thumbnail-url="createThumbnailUrl"
      >
        <NUploadDragger>
          <div class="m-32px">
            <NIcon size="48" :depth="3">
              <SvgIcon icon="flat-color-icons:upload" class="text-50px" />
            </NIcon>
          </div>
          <NText class="text-16px">点击或者拖动文件到该区域来上传</NText>
          <NP depth="3" class="mt-16px">请不要上传敏感数据，比如你的银行卡号和密码，信用卡号有效期和安全码</NP>
        </NUploadDragger>
      </NUpload>
    </NModal>
  </div>
</template>

<style scoped></style>
